<template>
  <player :dmSong="songlist"></player>
  <input v-model="rid" placeholder="请输入rid" />
  <button @click="startWs">提交</button>
  当前播放：{{this.curSong.song}}-{{this.curSong.singer}}<button @click="nextSong">切歌</button><button
    @click="pause">暂停</button>
  <div>
    <audio @timeupdate="handleTimeUpdate" @loadeddata="handleLoaded"
      :src="`https://dl.stream.qqmusic.qq.com/${playerData.url}`" ref="player" controls="controls" autoplay="autoplay"
      loop="loop"></audio>
  </div>
  <div style="color: #000;">
    {{this.connectStatus?"已连接":"未连接"}}
  </div>
  <div style="display: flex;">
    <div class="dm-content">
      <div class="dm" v-for="(item) in dm" :key="item" v-show="item.data.length&&item.data[0].nn">
        <div class="label">
          {{item.data.length&&item.data[0].nn?`${item.data[0].nn}`:""}}
        </div>
        {{item.data.length&&item.data[0].nn?`:`:""}}
        <div class="content">
          {{item.data.length&&item.data[0].nn?`${item.data[0].txt}`:""}}
        </div>
      </div>
    </div>
    <div class="music-list">
      <div v-for="item in songlist" :key="item.id">
        {{item.song}}-{{item.singer}}
      </div>
    </div>
  </div>
</template>

<script>
  import { getMusicList, getMusicUrl, changeSong } from "@/api/music"
  import player from "@/components/player/player.vue"
  export default {
    name: 'App',
    data() {
      return {
        socket: '',
        timer: "",
        rid: "",
        dm: [],
        songlist: [],
        curSong: {},
        playerData: {},
        connectStatus: false
      }
    },
    components: {
      player
    },
    mounted() {
    },
    methods: {
      startWs() {
        if (!this.rid) {
          return
        }
        this.dm = []
        this.socket&&this.socket.close()
        this.socket = new WebSocket(`ws://dm.cnpgu.com/dm/douyu`, 'mqtt')
        // this.socket = new WebSocket(`ws://127.0.0.1:3002/dm/douyu`, 'mqtt')
        this.socket.onopen = () => {
          this.socket.send(`{"type": "room","rid":${this.rid}}`);
          this.getMusic(this.songlist)
          this.connectStatus = true
        };
        this.socket.onerror = (e) => {
          console.log('error', e)
        };

        this.socket.onmessage = (e) => {
          // console.log(e)
          const data = JSON.parse(e.data)
          this.dm = [data, ...this.dm];
          if (data.data.length && data.data[0].type === 'chatmsg' && data.data[0].txt.indexOf('点歌') >= 0) {
            console.log(data.data[0].txt)
            this.timer = setInterval(() => {
              this.getMusic(this.songlist)
            }, 3000)
          }
        };

        this.socket.onclose = (e) => {
          this.connectStatus = false
          console.log(e)
        };
      },
      getMusic(list) {
        getMusicList({
          roomid: this.rid
        }).then(res => {
          console.log(res)
          this.songlist = res.data
          if (res.code === 200) {
            console.log(this.songlist, res)
            if (list.length != res.data.length) {
              clearInterval(this.timer)
            }
            if (this.songlist.length) {
              const { songid: songID, mid: songmid } = this.songlist[0]
              if (!this.curSong.songID) {
                this.curSong = {
                  ...this.songlist[0],
                  songID,
                  songmid
                }
                this.getCurrentMusic()
              }
            } else {
              this.curSong = {
              }
              this.playerData = {}
            }
          }
        })
      },
      nextSong() {
        console.log(this.curSong)
        changeSong({
          ...this.curSong,
          roomid: this.rid
        }).then(res => {
          console.log(res)
          if (res.code === 200) {
            this.$refs.player.pause()
            this.curSong = {}
            this.getMusic(this.songlist)
          }
        })
      },
      handleLoaded() {
        this.$refs.player.play()
        // 设置音量为50%
        this.$refs.player.volume = 0.5
      },
      pause() {
        if (!this.playerData.isPlay && this.playerData.url) {
          this.playerData.isPlay = true
          this.$refs.player.play()
        } else {
          this.playerData.isPlay = false
          this.$refs.player.pause()
        }
      },
      handleTimeUpdate(event) {
        if (event.target.currentTime + 1 >= this.$refs.player.duration) {
          this.playerData = {}
          this.nextSong()
        }
      },
      getCurrentMusic() {
        console.log(this.curSong)
        getMusicUrl({
          ...this.curSong
        }).then(res => {
          console.log(res)
          if (res.code === 0) {
            
            this.playerData.url = res.req_6.data.midurlinfo[0].purl
            // console.log(this.playerData)
            if (!this.playerData.url) {
              this.nextSong()
            }
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .dm {
    width: 500px;

  }

  .label {
    display: inline-block;
    width: 100px;
    text-align: right;
    color: #ff0000;
    font-size: 12px;
  }

  .content {
    display: inline-block;
    width: 300px;
    text-align: left;
    color: #000000;
    font-size: 12px;
  }
</style>